<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
//与数据库打交道的通用模型。增，删，改，查
class MY_Model extends CI_Model {
	protected $tbl;            //所有的表名的对象集合，总控制器和总模型各一套，则处处可用。保证了所有的表名都是用的配置里的。
	function __construct(){
		parent::__construct();
		$this->tbl = (object)config_item('tbl');
	}
	//数据保存。有id则更新并返回id的值，没有id则插入并返回插入的id值。
	function save($tbl,$data){

		//非表属性过滤
		$query = $this->db->query('desc '.$tbl);	//用查询语句获得表结构。
		
		$arr_all_field = array();		//收集表的全部字段
		foreach ($query->result() as $v){
			$arr_all_field[] = $v->Field;			
		}

		//过滤传入的有效数据
		$arr_field = array();
		$arr_value = array();
				
		foreach ($data as $k=>$v){
			if(in_array($k, $arr_all_field)){
				$arr_field[] = $k;
				$arr_value[] = $v;
			}
		}
		//过滤后的数据
		$datable = array();
		$datable = array_combine($arr_field,$arr_value);
		
		//判断有效数组中有没有id字段
		if(!empty($data['id'])){
			if(in_array('utime',$arr_all_field)) $datable['utime'] = time(); 
			$this->db->update($tbl,$datable,array('id'=>$data['id']));			
			return $data['id'];
		}else{
			if(in_array('atime',$arr_all_field)) $datable['atime'] = time(); 
			if(in_array('utime',$arr_all_field)) $datable['utime'] = time(); 
			$this->db->insert($tbl,$datable);
			return $this->db->insert_id();
		}
		
	}
	//根据id取得一条记录对象
	function get_by_id($tbl,$id){
		$query = $this->db->from($tbl)
			->where(array('id'=>$id))
			->get();
		return $query->row();
		
	}
	function row($tbl,$cond){
	    $query = $this->db->from($tbl)
			->where($cond)
			->get();
		return $query->row();
		
	}
	//根据条件取得对象或数组
	function get_all($tbl,$cond = array(),$type = 'obj'){
			$query = $this->db->from($tbl)
				->where($cond)
				->get();
		if($type == 'obj'){
			return $query->result();		
		}elseif($type == 'arr'){
			return $query->result_array();
		}
	}
	//根据条件删除
	function delete($tbl,$cond){
		return $this->db->delete($tbl,$cond);		
	}
	//根据字符串id批量删除。
	function delete_batch($tbl,$str_ids){
		$str_ids = trim($str_ids,',');
		$arr_id = explode(',', $str_ids);
		
		return $this->db->where_in('id',$arr_id)->delete($tbl);
		
	}
	
	
	
}